package org.umss.fixture.activities;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.umss.fixture.R;
import org.umss.fixture.model.Game;
import org.umss.fixture.model.Phase;
import org.umss.fixture.model.PhaseList;
import org.umss.fixture.model.Round;
import org.umss.fixture.services.FixtureBuilderServices;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ExpandableListView;

public class ShowPhasesActivity extends ActionBarActivity implements ActionBar.OnNavigationListener {

    private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
    private static ProgressDialog progressDialog;
    private List<String> phasesTitles;
    private PhaseList phasesList;
    private ActionBar actionBar;
    private String championshipName;
    ExpandableListAdapter listAdapter;
    ExpandableListView expListView;
    List<String> listDataHeader;
    HashMap<String, List<Game>> listDataChild;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_phases);
        actionBar = getSupportActionBar();
        phasesList = new PhaseList();
        phasesTitles = new ArrayList<String>();
        Bundle bundle = getIntent().getExtras();
        championshipName = bundle.getString("CHAMPIONSHIP_NAME");
        new LoadPhasesTask().execute(championshipName);
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
            getSupportActionBar().setSelectedNavigationItem(
                    savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getSupportActionBar()
                .getSelectedNavigationIndex());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.show_phases, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.newPhase) {
            Intent intent = new Intent(ShowPhasesActivity.this.getBaseContext(),
                    NewPhaseActivity.class);
            intent.putExtra("CHAMPIONSHIP_NAME", championshipName);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        if (id == R.id.scoreBoardMenu) {
            Intent intent = new Intent(ShowPhasesActivity.this.getBaseContext(),
                    ScoreBoardActivity.class);
            intent.putExtra("CHAMPIONSHIP_NAME", championshipName);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onNavigationItemSelected(int position, long id) {
        expListView = (ExpandableListView) findViewById(R.id.lvExp);
        prepareListData(phasesList.getPhases().get(position));
        listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
        expListView.setAdapter(listAdapter);
        expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
                    int childPosition, long id) {
                Game game = listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition);
                if (!game.isTerminated()) {
                    Intent intent = new Intent(ShowPhasesActivity.this.getBaseContext(),
                            GameResultActivity.class);
                    intent.putExtra("GAME_ID", game.getId());
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                }
                return true;
            }
        });
        return true;
    }

    private class LoadPhasesTask extends AsyncTask<String, Void, Void> {

        @Override
        public void onPreExecute() {
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(ShowPhasesActivity.this);
                progressDialog.setIndeterminate(true);
                progressDialog.setCancelable(false);
                progressDialog.setMessage("Retrieving phases...");
                progressDialog.show();
            }
        }

        @Override
        protected Void doInBackground(String... params) {
            String championshipName = params[0];
            FixtureBuilderServices fixtureBuilderServices = new FixtureBuilderServices();
            phasesList = fixtureBuilderServices.getAvailablePhases(championshipName);

            List<Phase> phases = phasesList.getPhases();

            for (int i = 0; i < phases.size(); i++) {
                phasesTitles.add("Phase - " + (i + 1));
            }

            return null;

        }

        @Override
        protected void onPostExecute(Void result) {
            actionBar.setDisplayShowTitleEnabled(false);
            actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
            actionBar.setListNavigationCallbacks(
                    new ArrayAdapter<String>(actionBar.getThemedContext(),
                            android.R.layout.simple_list_item_1, android.R.id.text1, phasesTitles),
                    ShowPhasesActivity.this);
            if (progressDialog != null) {
                progressDialog.dismiss();
            }

            progressDialog = null;
        }
    }

    private void prepareListData(Phase phase) {
        listDataHeader = new ArrayList<String>();
        listDataChild = new HashMap<String, List<Game>>();
        List<Round> rounds = phase.getRounds();
        for (int i = 0; i < rounds.size(); i++) {
            String roundName = "Round " + (i + 1);
            listDataHeader.add(roundName);
            List<Game> games = rounds.get(i).getGames();
            listDataChild.put(roundName, games);
        }
    }
}